package filter;


import page.SystemContext;
import util.StringUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class SystemContextFilter implements Filter {
    private Integer pageSize;

    public void destroy() {

    }

    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        Integer offset = 0;
        try {
           String page = req.getParameter("page");
            if(!StringUtil.isNullOrEmpty(page)){
                offset = Integer.parseInt(page);
            }
            String rows = req.getParameter("rows");
            if(!StringUtil.isNullOrEmpty(page)){
                pageSize = Integer.parseInt(rows);
            }
        } catch (NumberFormatException e) {

        }
        try {
            SystemContext.setOrder(req.getParameter("sord"));
            SystemContext.setSort(req.getParameter("sidx"));
            SystemContext.setPageOffset(offset);
            SystemContext.setPageSize(pageSize);
            SystemContext.setRealPath(((HttpServletRequest) req).getSession().getServletContext().getRealPath("/"));
            chain.doFilter(req, resp);
        } finally {
            SystemContext.removeOrder();
            SystemContext.removeSort();
            SystemContext.removePageOffset();
            SystemContext.removePageSize();
            SystemContext.removeRealPath();
        }
    }

    public void init(FilterConfig cfg) throws ServletException {

    }

}
